import 'package:flutter/material.dart';
import 'package:hm_pda_app/components/top_header.dart';
import 'package:hm_pda_app/config/http_request.dart';
import 'package:flutter_html/flutter_html.dart';
import 'package:hm_pda_app/components/loading_overlay.dart';

class InventoryLog extends StatefulWidget {
  const InventoryLog({super.key});

  @override
  State<InventoryLog> createState() => _InventoryLogState();
}

enum Calendar { bybatch, bysku }

class _InventoryLogState extends State<InventoryLog> {
  Calendar calendarView = Calendar.bybatch;
  bool isChecked = false;
  final _incomingGoodsController = TextEditingController();
  final _focusNode = FocusNode();
  // 声明列表数据
  List<SkuItem> listData = [];
  List<BatchItem> batchListData = [];

  // 获取查询数据-区分类型-按sku汇总
  Future<void> _getInventoryLogBySku() async {
    try {
      LoadingOverlay.show(context);
      final response = await HttpUtil.post(
        'storage/imSkuStorageSummaryRecord/admin/list',
        data: {
          'pageSize': 100,
          'pageNum': 1,
          'skuCode': _incomingGoodsController.text,
          'filterZeroStorageFlag': isChecked,
          // 'filterZeroStorageFlag': false,
        },
      );
      listData = [];
      final dataMap = response.data as Map<String, dynamic>;
      if (dataMap['rows'] != null && dataMap['rows'] is List) {
        List<dynamic> rows = dataMap['rows'];
        List<SkuItem> listData = rows.map((row) {
          return SkuItem(
            skuCode: row['skuCode'] ?? '',
            pictureUrl: row['pictureUrl'] ?? '',
            skuSalesStatusName: row['skuSalesStatusName'] ?? '',
            skuPackagingLengthSize: row['skuPackagingLengthSize'] ?? 0,
            skuPackagingWidthSize: row['skuPackagingWidthSize'] ?? 0,
            skuPackagingHeightSize: row['skuPackagingHeightSize'] ?? 0,
            skuGrossWeight: row['skuGrossWeight'] ?? 0,
            operationOrderNo: row['operationOrderNo'] ?? '',
            operationType: row['operationType'] ?? '',
            warehouseName: row['warehouseName'] ?? '',
            actualStockQuantityInfos: row['actualStockQuantityInfos'] ?? '',
            firstLegPlanQuantityInfo: row['firstLegPlanQuantityInfo'] ?? '',
            purchaseInTransitQuantityInfo:
                row['purchaseInTransitQuantityInfo'] ?? '',
            firstLegInTransitQuantityInfo:
                row['firstLegInTransitQuantityInfo'] ?? '',
            waitQualityCheckQuantityInfo:
                row['waitQualityCheckQuantityInfo'] ?? '',
            waitPutOnQuantityInfo: row['waitPutOnQuantityInfo'] ?? '',
            availableStockQuantityInfo: row['availableStockQuantityInfo'] ?? '',
            lockedStockQuantityInfo: row['lockedStockQuantityInfo'] ?? '',
            sellableQuantityInfo: row['sellableQuantityInfo'] ?? '',
            outOfStockQuantityInfo: row['outOfStockQuantityInfo'] ?? '',
            defectiveQuantityInfo: row['defectiveQuantityInfo'] ?? '',
          );
        }).toList();
        setState(() {
          this.listData = listData;
        });
      }
    } catch (error) {
      // 处理异常
      print('发生异常: $error');
    } finally {
      LoadingOverlay.hide();
    }
  }

  String showName(type) {
    const obj = {
      'sales_order_reserved': '销售订单占用',
      'sales_order_outbound': '销售订单出库',
      'overseas_warehouse_inventory_reserved': '海外仓货件占用',
      'overseas_warehouse_inventory_outbound': '海外仓货件出库',
      'inventory_surplus': '盘盈',
      'inventory_shortage': '盘亏',
      'purchase_order_placing': '采购下单',
      'purchase_order_inbound': '采购入库',
      'storage_lend_inbound': '借出单入库',
    };
    return obj[type] ?? '';
  }

  // 按批次汇总
  Future<void> _getInventoryLogByBatch(BuildContext context) async {
    try {
      LoadingOverlay.show(context);
      final response = await HttpUtil.post(
        '/storage/imSkuStorageBatchRecord/list',
        data: {
          'pageSize': 100,
          'pageNum': 1,
          'skuCode': _incomingGoodsController.text,
          'filterZeroStorageFlag': isChecked,
        },
      );
      batchListData = [];
      final dataMap = response.data as Map<String, dynamic>;
      if (dataMap['rows'] != null && dataMap['rows'] is List) {
        List<dynamic> rows = dataMap['rows'];
        List<BatchItem> listData = rows.map((row) {
          return BatchItem(
            skuCode: row['skuCode'] ?? '',
            pictureUrl: row['pictureUrl'] ?? '',
            skuChineseName: row['skuChineseName'] ?? '',
            purchaseOrderNo: row['purchaseOrderNo'] ?? '',
            storagePutOnSaleNo: row['storagePutOnSaleNo'] ?? '',
            warehouseName: row['warehouseName'] ?? '',
            operationOrderNo: row['operationOrderNo'] ?? '',
            operationTypeName: row['operationTypeName'] ?? '',
            locationCode: row['locationCode'] ?? '',
            firstPutOnStorageAge: (row['firstPutOnStorageAge'] ?? '')
                .toString(),
            lastPutOnStorageAge: (row['lastPutOnStorageAge'] ?? '').toString(),
            firstPutOnTime: row['firstPutOnTime'] ?? '',
            lastPutOnTime: row['lastPutOnTime'] ?? '',
            purchaseInTransitQuantityInfo:
                row['purchaseInTransitQuantityInfo'] ?? '',
            firstLegInTransitQuantityInfo:
                row['firstLegInTransitQuantityInfo'] ?? '',
            waitQualityCheckQuantityInfo:
                row['waitQualityCheckQuantityInfo'] ?? '',
            waitPutOnQuantityInfo: row['waitPutOnQuantityInfo'] ?? '',
            availableStockQuantityInfo: row['availableStockQuantityInfo'] ?? '',
            lockedStockQuantityInfo: row['lockedStockQuantityInfo'] ?? '',
            defectiveQuantityInfo: row['defectiveQuantityInfo'] ?? '',
            actualStockQuantityInfo: row['actualStockQuantityInfo'] ?? '',
          );
        }).toList();
        setState(() {
          this.batchListData = listData;
        });
      }
    } catch (error) {
      // 处理异常
      print('发生异常: $error');
    } finally {
      LoadingOverlay.hide();
    }
  }

  // 重置
  void _resetForm() {
    setState(() {
      // 取消操作，重置表单
      listData = [];
      batchListData = [];
      _incomingGoodsController.clear();
    });
    _focusNode.requestFocus();
  }

  @override
  void initState() {
    super.initState();
    _focusNode.requestFocus();
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      //appBar: AppBar(title: const Text("移库")),
      appBar: const TopHeader(title: '库存日志'),
      endDrawer: const CustomDrawer(),
      resizeToAvoidBottomInset: false,
      body: SingleChildScrollView(
        padding: EdgeInsets.all(1),
        child: Column(
          children: [
            Row(
              children: [
                Expanded(
                  child: Align(
                    alignment: Alignment.center,
                    child: SegmentedButton<Calendar>(
                      segments: const <ButtonSegment<Calendar>>[
                        ButtonSegment<Calendar>(
                          value: Calendar.bybatch,
                          label: Text('按批次明细查询'),
                        ),
                        ButtonSegment<Calendar>(
                          value: Calendar.bysku,
                          label: Text('按SKU汇总查询'),
                        ),
                      ],
                      selected: <Calendar>{calendarView},
                      onSelectionChanged: (Set<Calendar> newSelection) {
                        setState(() {
                          // By default there is only a single segment that can be
                          // selected at one time, so its value is always the first
                          // item in the selected set.
                          calendarView = newSelection.first;
                          if (calendarView == Calendar.bybatch) {
                            listData = [];
                          } else {
                            batchListData = [];
                          }
                        });
                      },
                    ),
                  ),
                ),
              ],
            ),
            Row(
              children: [
                Expanded(
                  flex: 1,
                  child: Align(
                    alignment: Alignment.topRight,
                    child: Checkbox(
                      tristate: false,
                      value: isChecked,
                      onChanged: (bool? value) {
                        setState(() {
                          isChecked = value ?? false;
                        });
                      },
                    ),
                  ),
                ),

                Expanded(
                  flex: 10,
                  child: Align(
                    alignment: Alignment.topLeft,
                    child: Text('是否显示0库存'),
                  ),
                ),
              ],
            ),

            const Divider(
              height: 2, // 容器总高度2像素
              thickness: 1, // 分割线厚度5像素
              indent: 0, // 左侧缩进20像素
              endIndent: 0, // 右侧无缩进
              color: Color.fromARGB(255, 109, 108, 108), // 黑色分割线
            ),
            Row(
              children: [
                Expanded(
                  flex: 2,
                  child: Align(
                    alignment: Alignment.center,
                    child: _buildLabel('仓库SKU', isRequired: true),
                  ),
                ),
                Expanded(
                  flex: 8,
                  child: Align(
                    alignment: Alignment.centerLeft,
                    child: TextFormField(
                      controller: _incomingGoodsController,
                      decoration: _buildInputDecoration(
                        hintText: '',
                        controller: _incomingGoodsController,
                        suffixIcon: ValueListenableBuilder<TextEditingValue>(
                          valueListenable: _incomingGoodsController,
                          builder: (context, value, child) {
                            return value.text.isEmpty
                                ? SizedBox.shrink()
                                : IconButton(
                                    icon: Icon(Icons.clear, size: 20),
                                    onPressed: () {
                                      _incomingGoodsController.clear();
                                    },
                                  );
                          },
                        ),
                      ),
                      focusNode: _focusNode,
                      onFieldSubmitted: (value) {
                        if (calendarView == Calendar.bybatch) {
                          _getInventoryLogByBatch(context);
                        } else {
                          _getInventoryLogBySku();
                        }
                        print('回车执行');
                      },
                    ),
                  ),
                ),
              ],
            ),
            batchListData.isNotEmpty && calendarView == Calendar.bybatch
                ? SizedBox(
                    child: _buildInfo(
                      //  _incomingGoodsController.text,
                      batchListData,
                      context,
                    ),
                  )
                : SizedBox(),
            listData.isNotEmpty && calendarView == Calendar.bysku
                ? SizedBox(
                    child: _buildSkuInfo(
                      //  _incomingGoodsController.text,
                      listData,
                      context,
                    ),
                  )
                : SizedBox(),

            // 添加库存列表展示
            const Divider(
              height: 2,
              thickness: 1,
              indent: 0,
              endIndent: 0,
              color: Color.fromARGB(255, 109, 108, 108),
            ),
            (batchListData.isNotEmpty || listData.isNotEmpty)
                ? Padding(
                    padding: const EdgeInsets.all(8.0),
                    child: Text(
                      '库存明细',
                      style: TextStyle(
                        fontSize: 18,
                        fontWeight: FontWeight.bold,
                        color: Colors.blue[700],
                      ),
                    ),
                  )
                : SizedBox(),
            calendarView == Calendar.bybatch ? _buildList() : _buildSkuList(),
          ],
        ),
      ),
      bottomNavigationBar: DecoratedBox(
        decoration: BoxDecoration(color: const Color.fromARGB(255, 77, 76, 76)),
        child: SizedBox(
          width: double.infinity,
          height: 50,
          child: Padding(
            padding: const EdgeInsets.symmetric(horizontal: 16.0),
            child: Row(
              children: [
                Expanded(
                  child: SizedBox(
                    height: 40,
                    child: OutlinedButton(
                      onPressed: () {
                        _resetForm();
                      },
                      style: OutlinedButton.styleFrom(
                        foregroundColor: Colors.white,
                        backgroundColor: Colors.grey[600],
                        side: BorderSide.none,
                        textStyle: const TextStyle(
                          fontSize: 16,
                          fontWeight: FontWeight.w500,
                        ),
                        shape: RoundedRectangleBorder(
                          borderRadius: BorderRadius.circular(12),
                        ),
                        elevation: 1,
                      ),
                      child: const Text('清除'),
                    ),
                  ),
                ),
                const SizedBox(width: 12),

                Expanded(
                  child: SizedBox(
                    height: 40,
                    child: ElevatedButton(
                      onPressed: () {
                        if (_incomingGoodsController.text.isEmpty) {
                          // 可以显示提示信息或直接返回
                          ScaffoldMessenger.of(
                            context,
                          ).showSnackBar(SnackBar(content: Text('请输入仓库SKU')));
                          return;
                        }

                        if (calendarView == Calendar.bybatch) {
                          _getInventoryLogByBatch(context);
                        } else {
                          _getInventoryLogBySku();
                        }
                      },
                      style: ElevatedButton.styleFrom(
                        backgroundColor: Colors.blue[600],
                        foregroundColor: Colors.white,
                        textStyle: const TextStyle(
                          fontSize: 16,
                          fontWeight: FontWeight.w600,
                        ),
                        shape: RoundedRectangleBorder(
                          borderRadius: BorderRadius.circular(12),
                        ),
                        elevation: 3,
                        // shadowColor: Colors.blue.withOpacity(0.3),
                      ),
                      child: const Text('提交'),
                    ),
                  ),
                ),
              ],
            ),
          ),
        ),
      ),
    );
  }

  // 列表数据展示-按批次明细汇总
  Widget _buildList() {
    return ListView.builder(
      shrinkWrap: true,
      physics: NeverScrollableScrollPhysics(),
      itemCount: batchListData.length,
      itemBuilder: (context, index) {
        final item = batchListData[index];
        return Card(
          margin: EdgeInsets.all(2),

          child: Column(
            children: [
              Row(
                children: [
                  Expanded(child: Text('采购单号:${item.operationOrderNo ?? ''}')),
                  Expanded(child: Text('上架单号:${item.operationOrderNo ?? ''}')),
                ],
              ),
              Row(
                children: [
                  Expanded(child: Text('操作单号:${item.operationOrderNo ?? ''}')),
                  Expanded(child: Text('类型:${item.operationTypeName ?? ''}')),
                ],
              ),
              Divider(
                height: 1,
                thickness: 1,
                indent: 0,
                endIndent: 0,
                color: Color.fromARGB(255, 109, 108, 108),
              ),
              Row(
                children: [
                  Expanded(child: Text('仓库:${item.warehouseName ?? ''}')),
                  Expanded(child: Text('库位:${item.locationCode ?? ''}')),
                ],
              ),
              Row(
                children: [
                  Expanded(
                    child: Text('首次库龄:${item.firstPutOnStorageAge ?? ''}'),
                  ),
                  Expanded(child: Text('首次上架:${item.firstPutOnTime ?? ''}')),
                ],
              ),
              Row(
                children: [
                  Expanded(
                    child: Text('最近库龄:${item.lastPutOnStorageAge ?? ''}'),
                  ),
                  Expanded(child: Text('最近上架:${item.lastPutOnTime ?? ''}')),
                ],
              ),
              Row(
                children: [
                  Expanded(
                    child: Html(
                      data: '采购在途:${item.purchaseInTransitQuantityInfo ?? ''}',
                    ),
                  ),
                  Expanded(
                    child: Html(
                      data: '首次在途:${item.firstLegInTransitQuantityInfo ?? ''}',
                    ),
                    // Text(
                    //   '首次在途:${item.firstLegInTransitQuantityInfo ?? ''}',
                    // ),
                  ),
                ],
              ),
              Row(
                children: [
                  Expanded(
                    child: Html(
                      data: '待质检:${item.waitQualityCheckQuantityInfo ?? ''}',
                    ),
                    // child: Text(
                    //   '待质检:${item.waitQualityCheckQuantityInfo ?? ''}',
                    // ),
                  ),
                  Expanded(
                    child: Html(
                      data: '待上架:${item.waitPutOnQuantityInfo ?? ''}',
                    ),
                    // child: Text('待上架:${item.waitPutOnQuantityInfo ?? ''}'),
                  ),
                ],
              ),
              Row(
                children: [
                  Expanded(
                    child: Html(
                      data: '可用库存:${item.availableStockQuantityInfo ?? ''}',
                    ),
                    // child: Text(
                    //   '待质检:${item.waitQualityCheckQuantityInfo ?? ''}',
                    // ),
                  ),
                  // Text('可用库存:${item.availableStockQuantityInfo ?? ''}'),
                  // Expanded(
                  //   child: Column(
                  //     children: [
                  //       Text('${item.availableStockQuantityInfo ?? ''}'),
                  //     ],
                  //   ),
                  // ),
                  Expanded(
                    child: Html(
                      data: '锁定库存:${item.lockedStockQuantityInfo ?? ''}',
                    ),
                    // child: Text(
                    //   '待质检:${item.waitQualityCheckQuantityInfo ?? ''}',
                    // ),
                  ),
                  // Text('锁定库存:${item.lockedStockQuantityInfo ?? ''}'),
                  // Expanded(
                  //   child: Column(
                  //     children: [Text('${item.lockedStockQuantityInfo ?? ''}')],
                  //   ),
                  // ),
                ],
              ),
              Row(
                children: [
                  Expanded(
                    child: Html(
                      data: '不良品:${item.defectiveQuantityInfo ?? ''}',
                    ),
                    // child: Text('不良品:${item.defectiveQuantityInfo ?? ''}'),
                  ),
                  Expanded(
                    child: Html(
                      data: '不良品:${item.actualStockQuantityInfo ?? ''}',
                    ),
                    // child: Text('实际库存:${item.actualStockQuantityInfo ?? ''}'),
                  ),
                ],
              ),
            ],
          ),
        );
      },
    );
  }

  // 按sku汇总展示
  Widget _buildSkuList() {
    return ListView.builder(
      shrinkWrap: true,
      physics: NeverScrollableScrollPhysics(),
      itemCount: listData.length,
      itemBuilder: (context, index) {
        final item = listData[index];
        return Card(
          margin: EdgeInsets.all(2),

          child: Column(
            children: [
              Row(
                children: [
                  Expanded(child: Text('操作单号:${item.operationOrderNo ?? ''}')),
                  Expanded(
                    child: Text('类型:${showName(item.operationType ?? '')}'),
                  ),
                ],
              ),
              Divider(
                height: 1,
                thickness: 1,
                indent: 0,
                endIndent: 0,
                color: Color.fromARGB(255, 109, 108, 108),
              ),
              Row(
                children: [
                  Expanded(child: Text('仓库:${item.warehouseName ?? ''}')),
                  Expanded(
                    child: Html(
                      data: '实际在库:${item.actualStockQuantityInfos ?? ''}',
                    ),
                    //child: Text('实际在库:${item.actualStockQuantityInfos ?? ''}'),
                  ),
                ],
              ),
              Row(
                children: [
                  Expanded(
                    // child: Text('采购计划:${item.purchasePlanQuantityInfo ?? ''}'),
                    child: Html(
                      data: '采购计划:${item.purchasePlanQuantityInfo ?? ''}',
                    ),
                  ),
                  Expanded(
                    // child: Text(
                    //   '采购在途:${item.purchaseInTransitQuantityInfo ?? ''}',
                    // ),
                    child: Html(
                      data: '采购在途:${item.purchaseInTransitQuantityInfo ?? ''}',
                    ),
                  ),
                ],
              ),
              Row(
                children: [
                  Expanded(
                    // child: Text('头程计划:${item.firstLegPlanQuantityInfo ?? ''}'),
                    child: Html(
                      data: '头程计划:${item.firstLegPlanQuantityInfo ?? ''}',
                    ),
                  ),
                  Expanded(
                    // child: Text(
                    //   '头程在途:${item.firstLegInTransitQuantityInfo ?? ''}',
                    // ),
                    child: Html(
                      data: '头程在途:${item.firstLegInTransitQuantityInfo ?? ''}',
                    ),
                  ),
                ],
              ),

              Row(
                children: [
                  Expanded(
                    // child: Html(
                    //   data: '待质检:${item.waitQualityCheckQuantityInfo ?? ''}',
                    // ),
                    child: Html(
                      data: '待质检:${item.waitQualityCheckQuantityInfo ?? ''}',
                    ),
                  ),
                  Expanded(
                    child: Html(
                      data: '待上架:${item.waitPutOnQuantityInfo ?? ''}',
                    ),
                    // child: Text('待上架:${item.waitPutOnQuantityInfo ?? ''}'),
                  ),
                ],
              ),
              Row(
                children: [
                  Expanded(
                    child: Html(
                      data: '可用库存:${item.availableStockQuantityInfo ?? ''}',
                    ),
                    // child: Text(
                    //   '待质检:${item.waitQualityCheckQuantityInfo ?? ''}',
                    // ),
                  ),

                  Expanded(
                    child: Html(
                      data: '锁定库存:${item.lockedStockQuantityInfo ?? ''}',
                    ),
                    // child: Text(
                    //   '待质检:${item.waitQualityCheckQuantityInfo ?? ''}',
                    // ),
                  ),
                ],
              ),
              Row(
                children: [
                  Expanded(
                    child: Html(
                      data: '可售库存:${item.sellableQuantityInfo ?? ''}',
                    ),
                    // child: Text('不良品:${item.defectiveQuantityInfo ?? ''}'),
                  ),
                  Expanded(
                    child: Html(
                      data: '缺货数:${item.outOfStockQuantityInfo ?? ''}',
                    ),
                    // child: Text('实际库存:${item.actualStockQuantityInfo ?? ''}'),
                  ),
                ],
              ),
              Row(
                children: [
                  Expanded(
                    child: Html(
                      data: '不良品:${item.defectiveQuantityInfo ?? ''}',
                    ),
                    // child: Text('不良品:${item.defectiveQuantityInfo ?? ''}'),
                  ),
                ],
              ),
            ],
          ),
        );
      },
    );
  }
}

// sku信息-批次明细
Widget _buildInfo(List batchDataList, BuildContext context) {
  return SizedBox(
    child: Row(
      children: [
        Expanded(
          flex: 2,
          child: Align(
            alignment: Alignment.centerLeft,
            child:
                batchDataList.isNotEmpty &&
                    batchDataList[0]!.pictureUrl!.isNotEmpty
                ? GestureDetector(
                    onTap: () {
                      _showImagePreview(context, batchDataList[0]!.pictureUrl!);
                    },
                    child: Image(
                      image: NetworkImage(batchDataList[0]!.pictureUrl!),
                      width: 100,
                      height: 100,
                      errorBuilder: (context, error, stackTrace) {
                        return Container(
                          width: 100,
                          height: 100,
                          color: Colors.grey[200],
                          child: Icon(
                            Icons.image_not_supported,
                            size: 50,
                            color: Colors.grey[400],
                          ),
                        );
                      },
                    ),
                  )
                : Container(
                    width: 100,
                    height: 100,
                    color: Colors.grey[200],
                    child: Icon(Icons.image, size: 50, color: Colors.grey[400]),
                  ),
          ),
        ),
        SizedBox(width: 1),
        Expanded(
          flex: 4,
          child: Align(
            alignment: Alignment.centerLeft,
            child: Column(
              children: [
                Row(
                  children: [
                    Expanded(
                      flex: 1,
                      child: Align(
                        alignment: Alignment.centerLeft,
                        child: Text('仓库SKU:${batchDataList[0].skuCode}'),
                      ),
                    ),
                  ],
                ),
                Row(
                  children: [
                    Expanded(
                      flex: 1,
                      child: Align(
                        alignment: Alignment.centerLeft,
                        child: Text(
                          '中文名称:${batchDataList[0].skuChineseName ?? ''}',
                        ),
                      ),
                    ),
                  ],
                ),
              ],
            ),
          ),
        ),
      ],
    ),
  );
}

Widget _buildSkuInfo(List dataList, BuildContext context) {
  return SizedBox(
    child: Row(
      children: [
        Expanded(
          flex: 2,
          child: Align(
            alignment: Alignment.centerLeft,
            child: dataList.isNotEmpty && dataList[0]!.pictureUrl!.isNotEmpty
                ? GestureDetector(
                    onTap: () {
                      _showImagePreview(context, dataList[0]!.pictureUrl!);
                    },
                    child: Image(
                      image: NetworkImage(dataList[0]!.pictureUrl!),
                      width: 100,
                      height: 100,
                      errorBuilder: (context, error, stackTrace) {
                        return Container(
                          width: 100,
                          height: 100,
                          color: Colors.grey[200],
                          child: Icon(
                            Icons.image_not_supported,
                            size: 50,
                            color: Colors.grey[400],
                          ),
                        );
                      },
                    ),
                  )
                : Container(
                    width: 100,
                    height: 100,
                    color: Colors.grey[200],
                    child: Icon(Icons.image, size: 50, color: Colors.grey[400]),
                  ),
          ),
        ),
        SizedBox(width: 1),
        Expanded(
          flex: 4,
          child: Align(
            alignment: Alignment.centerLeft,
            child: Column(
              children: [
                Row(
                  children: [
                    Expanded(
                      flex: 1,
                      child: Align(
                        alignment: Alignment.centerLeft,
                        child: Text('仓库SKU:${dataList[0].skuCode}'),
                      ),
                    ),
                  ],
                ),
                Row(
                  children: [
                    Expanded(
                      flex: 1,
                      child: Align(
                        alignment: Alignment.centerLeft,
                        child: Text(
                          '尺寸:${dataList[0].skuPackagingLengthSize ?? ''}×${dataList[0].skuPackagingWidthSize ?? ''}×${dataList[0].skuPackagingHeightSize ?? ''}',
                        ),
                      ),
                    ),
                  ],
                ),
                Row(
                  children: [
                    Expanded(
                      flex: 1,
                      child: Align(
                        alignment: Alignment.centerLeft,
                        child: Text('重量:${dataList[0].skuGrossWeight ?? ''}kg'),
                      ),
                    ),
                  ],
                ),
                Row(
                  children: [
                    Expanded(
                      flex: 1,
                      child: Align(
                        alignment: Alignment.centerLeft,
                        child: Text(
                          '销售状态:${dataList[0].skuSalesStatusName ?? ''}',
                        ),
                      ),
                    ),
                  ],
                ),
              ],
            ),
          ),
        ),
      ],
    ),
  );
}

void _showImagePreview(BuildContext context, String imageUrl) {
  showDialog(
    context: context,
    builder: (BuildContext context) {
      return Dialog(
        backgroundColor: Colors.transparent,
        child: Stack(
          children: [
            Center(
              child: InteractiveViewer(
                panEnabled: true, // 允许拖拽
                boundaryMargin: EdgeInsets.all(20),
                minScale: 0.1,
                maxScale: 6.0,
                child: SizedBox(
                  width: MediaQuery.of(context).size.width * 0.9,
                  child: Image.network(
                    imageUrl,
                    fit: BoxFit.contain,
                    errorBuilder: (context, error, stackTrace) {
                      return Container(
                        padding: EdgeInsets.all(20),
                        child: Column(
                          mainAxisSize: MainAxisSize.min,
                          children: [
                            Icon(Icons.error, size: 50, color: Colors.white),
                            SizedBox(height: 10),
                            Text(
                              '图片加载失败',
                              style: TextStyle(color: Colors.white),
                            ),
                          ],
                        ),
                      );
                    },
                  ),
                ),
              ),
            ),
            Positioned(
              top: 40,
              right: 20,
              child: GestureDetector(
                onTap: () => Navigator.of(context).pop(),
                child: Container(
                  width: 40,
                  height: 40,
                  decoration: BoxDecoration(
                    color: Colors.black54,
                    shape: BoxShape.circle,
                  ),
                  child: Icon(Icons.close, color: Colors.white, size: 24),
                ),
              ),
            ),
          ],
        ),
      );
    },
  );
}

// 构建标签文本
Widget _buildLabel(String text, {bool isRequired = false}) {
  return SizedBox(
    // width: 200,
    child: Padding(
      padding: EdgeInsets.symmetric(horizontal: 2),
      child: Text(
        text,
        style: TextStyle(
          fontWeight: FontWeight.w500,
          fontSize: 16,
          color: isRequired ? Colors.red : Colors.grey[700],
        ),
      ),
    ),
  );
}

// 构建输入框装饰
InputDecoration _buildInputDecoration({
  required String hintText,
  required TextEditingController controller,
  Widget? suffixIcon,
}) {
  print('controller ${controller.text}');
  return InputDecoration(
    hintText: hintText,
    contentPadding: EdgeInsets.zero, // 设置上下左右内边距都为0
    // prefixIcon: Icon(prefixIcon, color: Colors.grey[600]),
    suffixIcon: suffixIcon,
    hintStyle: TextStyle(color: Colors.grey[500]),
    // isDense: true 属性用于减少输入框的垂直高度，使其更紧凑
    // 当设置为 true 时，会减少内边距，让输入框看起来更小更密集
    // 适用于需要节省空间或创建更紧凑布局的场景
    // isDense: true,
    filled: true,
    fillColor: Colors.grey[50],

    // suffixIcon: controller.text.isNotEmpty
    //             ? IconButton(
    //                 icon: Icon(Icons.clear, size: 20),
    //                 onPressed: () {
    //                   controller.clear();
    //                   // 需要通知父组件状态更新
    //                   if (mounted) {
    //                     setState(() {});
    //                   }
    //                 },
    //               )
    //             : null,
    border: OutlineInputBorder(
      borderRadius: BorderRadius.circular(8),
      borderSide: BorderSide(color: Colors.grey[300]!),
    ),
    enabledBorder: OutlineInputBorder(
      borderRadius: BorderRadius.circular(8),
      borderSide: BorderSide(color: Colors.grey[300]!),
    ),
    focusedBorder: OutlineInputBorder(
      borderRadius: BorderRadius.circular(8),
      borderSide: BorderSide(color: Colors.blue, width: 2),
    ),
    errorBorder: OutlineInputBorder(
      borderRadius: BorderRadius.circular(8),
      borderSide: BorderSide(color: Colors.red),
    ),
    focusedErrorBorder: OutlineInputBorder(
      borderRadius: BorderRadius.circular(8),
      borderSide: BorderSide(color: Colors.red, width: 2),
    ),
  );
}

// 列表数据结构
class ListItem {
  final String purchaseOrderCode;
  final String shelvingOrderCode;
  final String warehouseCode;
  final String locationCode;
  final DateTime? firstStockAge;
  final DateTime? firstShelving;
  final DateTime? recentStockAge;
  final DateTime? recentShelving;
  final num purchaseInTransit;
  final num firstLegInTransit;
  final num pendingQualityCheck;
  final num pendingShelving;
  final num availableStock;
  final num lockedStock;
  final num defectiveStock;
  final num actualStock;
  ListItem({
    required this.purchaseOrderCode,
    required this.shelvingOrderCode,
    required this.warehouseCode,
    required this.locationCode,
    required this.firstStockAge,
    required this.firstShelving,
    required this.recentStockAge,
    required this.recentShelving,
    required this.purchaseInTransit,
    required this.firstLegInTransit,
    required this.pendingQualityCheck,
    required this.pendingShelving,
    required this.availableStock,
    required this.lockedStock,
    required this.defectiveStock,
    required this.actualStock,
  });
}

class SkuItem {
  final String? skuCode;
  final String? pictureUrl;
  final String? skuSalesStatusName;
  final num? skuPackagingLengthSize;
  final num? skuPackagingWidthSize;
  final num? skuPackagingHeightSize;
  final num? skuGrossWeight;
  final String? operationOrderNo;
  final String? operationType;
  final String? warehouseName;
  final String? actualStockQuantityInfos;
  final String? firstLegPlanQuantityInfo;
  final String? purchaseInTransitQuantityInfo;

  final String? firstLegInTransitQuantityInfo;
  final String? waitQualityCheckQuantityInfo;
  final String? waitPutOnQuantityInfo;
  final String? availableStockQuantityInfo;
  final String? lockedStockQuantityInfo;

  final String? sellableQuantityInfo;
  final String? outOfStockQuantityInfo;
  final String? defectiveQuantityInfo;
  final String? purchasePlanQuantityInfo;
  SkuItem({
    this.skuCode,
    this.pictureUrl,
    this.skuSalesStatusName,
    this.skuPackagingLengthSize,
    this.skuPackagingWidthSize,
    this.skuPackagingHeightSize,
    this.skuGrossWeight,
    this.operationOrderNo,
    this.operationType,
    this.warehouseName,
    this.actualStockQuantityInfos,
    this.firstLegPlanQuantityInfo,
    this.purchaseInTransitQuantityInfo,
    this.firstLegInTransitQuantityInfo,
    this.waitQualityCheckQuantityInfo,
    this.waitPutOnQuantityInfo,
    this.availableStockQuantityInfo,
    this.lockedStockQuantityInfo,
    this.sellableQuantityInfo,
    this.outOfStockQuantityInfo,
    this.defectiveQuantityInfo,
    this.purchasePlanQuantityInfo,
  });

  factory SkuItem.fromJson(Map<String, dynamic> json) {
    return SkuItem(
      skuCode: json['skuCode'] ?? '',
      pictureUrl: json['pictureUrl'] ?? '',
      skuSalesStatusName: json['skuSalesStatusName'] ?? '',
      skuPackagingLengthSize: json['skuPackagingLengthSize'] ?? 0,
      skuPackagingWidthSize: json['skuPackagingWidthSize'] ?? 0,
      skuPackagingHeightSize: json['skuPackagingHeightSize'] ?? 0,
      skuGrossWeight: json['skuGrossWeight'] ?? 0,
      operationOrderNo: json['operationOrderNo'] ?? '',
      operationType: json['operationType'] ?? '',
      warehouseName: json['warehouseName'] ?? '',
      actualStockQuantityInfos: json['actualStockQuantityInfos'] ?? '',
      firstLegPlanQuantityInfo: json['firstLegPlanQuantityInfo'] ?? '',
      purchaseInTransitQuantityInfo:
          json['purchaseInTransitQuantityInfo'] ?? '',
      firstLegInTransitQuantityInfo:
          json['firstLegInTransitQuantityInfo'] ?? '',
      waitQualityCheckQuantityInfo: json['waitQualityCheckQuantityInfo'] ?? '',
      waitPutOnQuantityInfo: json['waitPutOnQuantityInfo'] ?? '',
      availableStockQuantityInfo: json['availableStockQuantityInfo'] ?? '',
      lockedStockQuantityInfo: json['lockedStockQuantityInfo'] ?? '',
      sellableQuantityInfo: json['sellableQuantityInfo'] ?? '',
      outOfStockQuantityInfo: json['outOfStockQuantityInfo'] ?? '',
      defectiveQuantityInfo: json['defectiveQuantityInfo'] ?? '',
      purchasePlanQuantityInfo: json['purchasePlanQuantityInfo'] ?? '',
    );
  }

  Map<String, dynamic> toJson() {
    return {
      'skuCode': skuCode,
      'pictureUrl': pictureUrl,
      'skuSalesStatusName': skuSalesStatusName,
      'skuPackagingLengthSize': skuPackagingLengthSize,
      'skuPackagingWidthSize': skuPackagingWidthSize,
      'skuPackagingHeightSize': skuPackagingHeightSize,
      'skuGrossWeight': skuGrossWeight,
      'operationOrderNo': operationOrderNo,
      'operationType': operationType,
      'warehouseName': warehouseName,
      'actualStockQuantityInfos': actualStockQuantityInfos,
      'firstLegPlanQuantityInfo': firstLegPlanQuantityInfo,
      'purchaseInTransitQuantityInfo': purchaseInTransitQuantityInfo,
      'firstLegInTransitQuantityInfo': firstLegInTransitQuantityInfo,
      'waitQualityCheckQuantityInfo': waitQualityCheckQuantityInfo,
      'waitPutOnQuantityInfo': waitPutOnQuantityInfo,
      'availableStockQuantityInfo': availableStockQuantityInfo,
      'lockedStockQuantityInfo': lockedStockQuantityInfo,
      'sellableQuantityInfo': sellableQuantityInfo,
      'outOfStockQuantityInfo': outOfStockQuantityInfo,
      'defectiveQuantityInfo': defectiveQuantityInfo,
      'purchasePlanQuantityInfo': purchasePlanQuantityInfo,
    };
  }
}

class BatchItem {
  final String? skuCode;
  final String? pictureUrl;
  final String? skuChineseName;
  final String? purchaseOrderNo;
  final String? storagePutOnSaleNo;
  final String? warehouseName;
  final String? operationOrderNo;
  final String? operationTypeName;
  final String? locationCode;
  final String? firstPutOnStorageAge;
  final String? lastPutOnStorageAge;
  final String? firstPutOnTime;
  final String? lastPutOnTime;
  final String? purchaseInTransitQuantityInfo;
  final String? firstLegInTransitQuantityInfo;
  final String? waitQualityCheckQuantityInfo;
  final String? waitPutOnQuantityInfo;
  final String? availableStockQuantityInfo;
  final String? lockedStockQuantityInfo;
  final String? defectiveQuantityInfo;
  final String? actualStockQuantityInfo;
  BatchItem({
    this.skuCode,
    this.pictureUrl,
    this.skuChineseName,
    this.purchaseOrderNo,
    this.storagePutOnSaleNo,
    this.warehouseName,
    this.operationOrderNo,
    this.operationTypeName,
    this.locationCode,
    this.firstPutOnStorageAge,
    this.lastPutOnStorageAge,
    this.firstPutOnTime,
    this.lastPutOnTime,
    this.purchaseInTransitQuantityInfo,
    this.firstLegInTransitQuantityInfo,
    this.waitQualityCheckQuantityInfo,
    this.waitPutOnQuantityInfo,
    this.availableStockQuantityInfo,
    this.lockedStockQuantityInfo,
    this.defectiveQuantityInfo,
    this.actualStockQuantityInfo,
  });
  factory BatchItem.fromJson(Map<String, dynamic> json) {
    return BatchItem(
      skuCode: json['skuCode'] ?? '',
      pictureUrl: json['pictureUrl'] ?? '',
      skuChineseName: json['skuChineseName'] ?? '',
      purchaseOrderNo: json['purchaseOrderNo'] ?? '',
      storagePutOnSaleNo: json['storagePutOnSaleNo'] ?? '',
      warehouseName: json['warehouseName'] ?? '',
      operationOrderNo: json['operationOrderNo'] ?? '',
      operationTypeName: json['operationTypeName'] ?? '',
      locationCode: json['locationCode'] ?? '',
      firstPutOnStorageAge: json['firstPutOnStorageAge'] ?? '',
      lastPutOnStorageAge: json['lastPutOnStorageAge'] ?? '',
      firstPutOnTime: json['firstPutOnTime'] ?? '',
      lastPutOnTime: json['lastPutOnTime'] ?? '',
      purchaseInTransitQuantityInfo:
          json['purchaseInTransitQuantityInfo'] ?? '',
      firstLegInTransitQuantityInfo:
          json['firstLegInTransitQuantityInfo'] ?? '',
      waitQualityCheckQuantityInfo: json['waitQualityCheckQuantityInfo'] ?? '',
      waitPutOnQuantityInfo: json['waitPutOnQuantityInfo'] ?? '',
      availableStockQuantityInfo: json['availableStockQuantityInfo'] ?? '',
      lockedStockQuantityInfo: json['lockedStockQuantityInfo'] ?? '',
      defectiveQuantityInfo: json['defectiveQuantityInfo'] ?? '',
      actualStockQuantityInfo: json['actualStockQuantityInfo'] ?? '',
    );
  }

  Map<String, dynamic> toJson() {
    return {
      'skuCode': skuCode,
      'pictureUrl': pictureUrl,
      'skuChineseName': skuChineseName,
      'purchaseOrderNo': purchaseOrderNo,
      'storagePutOnSaleNo': storagePutOnSaleNo,
      'warehouseName': warehouseName,
      'operationOrderNo': operationOrderNo,
      'operationTypeName': operationTypeName,
      'locationCode': locationCode,
      'firstPutOnStorageAge': firstPutOnStorageAge,
      'lastPutOnStorageAge': lastPutOnStorageAge,
      'firstPutOnTime': firstPutOnTime,
      'lastPutOnTime': lastPutOnTime,
      'purchaseInTransitQuantityInfo': purchaseInTransitQuantityInfo,
      'firstLegInTransitQuantityInfo': firstLegInTransitQuantityInfo,
      'waitQualityCheckQuantityInfo': waitQualityCheckQuantityInfo,
      'waitPutOnQuantityInfo': waitPutOnQuantityInfo,
      'availableStockQuantityInfo': availableStockQuantityInfo,
      'lockedStockQuantityInfo': lockedStockQuantityInfo,
      'defectiveQuantityInfo': defectiveQuantityInfo,
      'actualStockQuantityInfo': actualStockQuantityInfo,
    };
  }
}
